package com.controller;



import com.Util.PdfUtils;
import com.entity.Document;
import com.entity.base.Result;
import com.service.DocumentService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@RestController
@RequestMapping(value = "/document")
@Slf4j
@Api(tags = "文件相关接口", description = "提供相关的 Rest API")
public class DocumentController extends BaseController<Document, DocumentService>{

    @Autowired
    DocumentService documentService;

    @Autowired
    private PdfUtils pdfUtils;

    @ApiOperation("获取文件树接口")
    @GetMapping("/findTree")
    public Result findList(){
        List<Document> list = documentService.treeList();
        if (list.size()>0)
            return Result.success(list);
        else return Result.error("查询失败");
    }

    @ApiOperation("删除文件/文件夹")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "document", value = "文件实体", required = true, dataType = "document", paramType = "body")
    })
    public Result delete(@RequestBody Document document){
        long id = document.getId();
        if (id!=0){
            if (documentService.removeById(id)){
                documentService.remakeDocument();
                return Result.success();
            }
            else return Result.error("删除失败");
        }
        return Result.error("删除失败");
    }

    @ApiOperation("转化为图片并阅览")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "document", value = "文件实体", required = true, dataType = "document", paramType = "body")
    })
    @PostMapping("topng")
    public Result toPng(@RequestBody Document document) throws Exception {
        String originalUrl = document.getPath();
        if (document.getPath()==null) {
            return Result.error("文件查找失败");
        }

        pdfUtils.toPdf(pdfUtils.getServerPath(originalUrl));

        int page = pdfUtils.pdf2Image(pdfUtils.getServerPath(pdfUtils.getPDFUrl(originalUrl)),96);
        Map<String, Object> data = new HashMap<>();
        data.put("src", originalUrl);
        data.put("pdfPath", pdfUtils.getPDFUrl(originalUrl));
        data.put("pngNum",page);
        data.put("pngList",pdfUtils.getPngUrl(originalUrl,page));
        return Result.success(data);
    }

    @ApiOperation("转化为图片并阅览")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "url", value = "文件路径", required = true, dataType = "String", paramType = "String")
    })
    @GetMapping("/download")
    public String fileDownLoad(HttpServletResponse response,String url) throws Exception {
        File file = new File(System.getProperty("user.dir")+url);
        if (!file.exists()) {
            return "下载文件不存在";
        }
        response.reset();
        response.setContentType("application/octet-stream");
        response.setCharacterEncoding("utf-8");
        response.setContentLength((int) file.length());
        // 设置编码格式
        response.setHeader("Content-Disposition",
                "attachment;fileName=" + URLEncoder.encode(file.getName(), "UTF-8"));
        BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));
        byte[] buff = new byte[1024];
        OutputStream os = response.getOutputStream();
        int i = 0;
        while ((i = bis.read(buff)) != -1) {
            os.write(buff, 0, i);
            os.flush();
        }
        bis.close();
        os.close();
        return "下载成功";
    }
}
